use clap::Parser;
use log::LevelFilter;
use rust_mq_client::{
    cli::Cli,
    command::{
        consume::consume, create_topic::create_topic, delete_topic::delete_topic, list::list, produce::produce
    },
    error::Error,
};
use std::str::FromStr;
use std::{env, net::SocketAddr};
use tokio::net::TcpStream;

#[tokio::main]
async fn main() -> Result<(), Error> {
    init_log();

    let mut cli = Cli::parse();

    let socket_addr = format!("{}:{}", cli.ip, cli.port)
        .parse::<SocketAddr>()
        .unwrap();
    let stream: TcpStream = TcpStream::connect(socket_addr).await?;

    match cli.command.as_str() {
        "create_topic" => {
            if 0 == cli.partitions {
                cli.partitions = 3;
            }
            create_topic(stream, &cli).await?;
        }
        "consume" => {
            consume(stream, &cli).await?;
        }
        "delete_topic" => {
            delete_topic(stream, &cli).await?;
        }
        "produce" => {
            produce(stream, &cli).await?;
        },
        "list" => {
            list(stream, &cli).await?;
        }
        _ => {}
    };

    Ok(())
}

fn init_log() {
    let log_level = match env::var("RUST_LOG") {
        Ok(val) => val,
        Err(_) => "info".to_string(),
    };

    let level_filter = match LevelFilter::from_str(&log_level) {
        Ok(filter) => filter,
        Err(_) => LevelFilter::Info, // Default to Info if parsing fails
    };

    // Configure logger
    env_logger::builder().filter_level(level_filter).init();
}
